<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/12/5
 * Time: 11:55
 */

namespace Shop\Api;


use Api\Vendor\NetWarehourse\WHOrderStatus;
use Common\Api\Api;
use Shop\Model\OrdersModel;
use Shop\Model\OrderStatusHistoryModel;

/**
 * 浙江电子口岸状态统一操作
 * Class WMSOrderStatusApi
 * @package Shop\Api\
 */
class ZjportOrderStatusApi extends Api  {


    /**
     * 1. 更新状态
     */
    const UPDATE_STATUS = "Shop/ZjportOrderStatus/update_status";

    protected function _init(){

        $this->model = new OrdersModel();

    }

    /**
     * 9. 订单 拣选状态
     * @param $order_code
     * @return array
     */
    public function update_status($order_code,$next_status,$reason){

        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->apiReturnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->apiReturnErr("订单ID错误!");
        }

        $cur_status = $result['zjport_status'];

        $reason  = "海关回执(".$reason."),".getZjportStatus($next_status);

        $entity = array(
            'reason'=>$reason,
            'order_code'=>$order_code,
            'operator'=>0,
            'status_type'=>strtoupper(OrderStatusHistoryModel::STATUS_TYPE_ZJPORT),
            'isauto'=>1,
            'cur_status'=> $cur_status,
            'next_status'=> $next_status,
        );

        $orderStatusHistoryModel = new OrderStatusHistoryModel();
        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('zjport_status'=> $next_status ));

        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }


        if($orderStatusHistoryModel->create($entity,1)){
            $result = $orderStatusHistoryModel->add();
            if($result === false){
                $flag = false;
                $return = $orderStatusHistoryModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderStatusHistoryModel->getError();
        }

        if($flag){
            $this->model->commit();
            return $this->apiReturnSuc($return);
        }else{
            $this->model->rollback();
            return $this->apiReturnErr($return);
        }
    }

}